package TextEditor;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;

/**
 * @Author mao
 * @Date 2025/11/15
 * @Description 通过输入输出流实现仿记事本程序
 */
public class NotepadApp extends JFrame {
    // 文件路径框
    private JTextField filePathField;
    // 文本编辑框
    private JTextArea textArea;
    // 功能按钮
    private JButton openButton, saveButton, saveAsButton, newButton;

    public NotepadApp() {
        setTitle("记事本App - 点击「打开」按钮开始编辑文件");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());
        JPanel topPanel = new JPanel();
        topPanel.setLayout(new FlowLayout(FlowLayout.LEFT));

        JLabel label = new JLabel("文件路径：");
        filePathField = new JTextField(getDefaultFile(), 30);
        openButton = new JButton("打开");
        saveButton = new JButton("保存");
        saveAsButton = new JButton("另存");
        newButton = new JButton("新建");

        topPanel.add(label);
        topPanel.add(filePathField);
        topPanel.add(openButton);
        topPanel.add(saveButton);
        topPanel.add(saveAsButton);
        topPanel.add(newButton);

        // 文本编辑区
        textArea = new JTextArea(20, 60);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        JScrollPane scrollPane = new JScrollPane(textArea);
        add(topPanel, BorderLayout.NORTH);
        add(scrollPane, BorderLayout.CENTER);

        // 绑定事件
        openButton.addActionListener(new OpenAction());
        saveButton.addActionListener(new SaveAction());
        saveAsButton.addActionListener(new SaveAsAction());
        newButton.addActionListener(new NewAction());

        pack();
        setLocationRelativeTo(null);
    }

    // 打开文件后更新窗口标题
    private void updateTitle(String fullPath) {
        if (fullPath == null || fullPath.trim().isEmpty()) {
            setTitle("记事本App - 未选定文件");
        } else {
            File file = new File(fullPath.trim());
            setTitle("记事本App - " + file.getName());
        }
    }

    // 获取默认文件地址-且基于不同系统规范拼接地址
    private String getDefaultFile() {
        return System.getProperty("user.dir") + File.separator + "TextEditor"+ File.separator + "about.txt";
    }


    // 实现按钮功能
    class NewAction implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String input = JOptionPane.showInputDialog(
                    NotepadApp.this,
                    "请输入新文件的完整路径",
                    "新建文件",
                    JOptionPane.PLAIN_MESSAGE
            );
            if (input == null || input.trim().isEmpty()) {
                // 用户取消或未输入
                return;
            }
            String fullPath = input.trim();
            File file = new File(fullPath);
            File parentDir = file.getParentFile();

            try {
                // 创建父目录（如果不存在）
                if (parentDir != null && !parentDir.exists()) {
                    if (!parentDir.mkdirs()) {
                        throw new IOException("无法创建目录: " + parentDir.getAbsolutePath());
                    }
                }

                // 文件存在则打开，不存在则创建
                if (file.exists()) {
                    try (BufferedReader reader = new BufferedReader(
                            new InputStreamReader(new FileInputStream(file), "UTF-8"))) {
                        StringBuilder content = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            content.append(line).append("\n");
                        }
                        textArea.setText(content.toString());
                        updateTitle(fullPath);
                        filePathField.setText(fullPath);
                        JOptionPane.showMessageDialog(NotepadApp.this,
                                "文件已存在 打开成功\n路径: " + fullPath,
                                "提示",
                                JOptionPane.INFORMATION_MESSAGE);
                    } catch (IOException ex) {
                        throw new IOException("打开文件失败: " + ex.getMessage(), ex);
                    }
                } else {
                    // 文件不存在时
                    if (!file.createNewFile()) {
                        throw new IOException("无法创建文件: " + fullPath);
                    }
                    // 更新界面状态
                    filePathField.setText(fullPath);
                    textArea.setText("");
                    updateTitle(fullPath);
                    JOptionPane.showMessageDialog(NotepadApp.this,
                            "新建文件成功！\n路径: " + fullPath,
                            "提示",
                            JOptionPane.INFORMATION_MESSAGE);
                }
            } catch (IOException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(
                        NotepadApp.this,
                        "操作失败：\n" + ex.getMessage(),
                        "错误",
                        JOptionPane.ERROR_MESSAGE
                );
            }
        }
    }

    class OpenAction implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String path = filePathField.getText().trim();
            if (path.isEmpty()) {
                JOptionPane.showMessageDialog(NotepadApp.this, "请输入文件路径！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            File file = new File(path);
            if (!file.exists()) {
                JOptionPane.showMessageDialog(NotepadApp.this, "文件不存在！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) {
                StringBuilder content = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    content.append(line).append("\n");
                }
                textArea.setText(content.toString());
                updateTitle(path);
            } catch (IOException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(NotepadApp.this, "读取文件失败：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    class SaveAction implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String path = filePathField.getText().trim();
            if (path.isEmpty()) {
                JOptionPane.showMessageDialog(NotepadApp.this, "请输入文件路径！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path), "UTF-8"))) {
                writer.write(textArea.getText());
                JOptionPane.showMessageDialog(NotepadApp.this, "文件保存成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
                updateTitle(path);
            } catch (IOException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(NotepadApp.this, "保存文件失败：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    class SaveAsAction implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            // 使用JFileChooser-文件选择器
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setDialogTitle("另存为");
            int result = fileChooser.showSaveDialog(NotepadApp.this);
            if (result == JFileChooser.APPROVE_OPTION) {
                File selectedFile = fileChooser.getSelectedFile();
                try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(selectedFile), "UTF-8"))) {
                    writer.write(textArea.getText());
                    filePathField.setText(selectedFile.getAbsolutePath());
                    updateTitle(selectedFile.getAbsolutePath());
                    JOptionPane.showMessageDialog(NotepadApp.this, "文件另存成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
                } catch (IOException ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(NotepadApp.this, "另存失败：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }

    public static void main(String[] args) {
        // new NotepadApp().setVisible(true);
        // 使用Swing推荐的在事件调度线程中运行
        SwingUtilities.invokeLater(() -> new NotepadApp().setVisible(true));
    }
}
